
import os
import re
import xlrd
import xlwt
import re
import sys

def get_conf_file(path):
    print('path=', path)
    f=''
    for item in os.listdir(path):
        if '.xls' in item  or  '.xlsx' in item:
            f=item
            break
    return   f


def update_conf(path  ):    ##update the configure excel file, support two layers only at present
    conf_file=get_conf_file(path)
    workbook = xlrd.open_workbook( os.path.join(path, conf_file) )
    sheet = workbook.sheet_by_index(0)
    out_workbook=xlwt.Workbook(encoding = 'ascii')
    outsheet = out_workbook.add_sheet('My Worksheet',  cell_overwrite_ok=True)

    for i in range(0,sheet.nrows):
        for j in range(0, sheet.ncols):
            outsheet.write(i,j, sheet.cell(i, j).value )

    for i in range(4, sheet.nrows):
        #chapter = re.findall(r'第(.{1,2})章', sheet.cell(i, 0).value)
        if '章' in sheet.cell(i, 0).value:
            index1=get_index1(sheet.cell(i, 0).value)
            outsheet.write(i,1, index1)
            index2=1
            for j in range(i+1, sheet.nrows):
                if '章' in sheet.cell(j, 0).value:
                    i=j-1
                    break
                #index2=get_index2(sheet.cell(j, 0).value, index1)
                print('index1,2=',index1, index2)
                outsheet.write(j, 1, index1)
                outsheet.write(j, 2, index2)
                ti_counts=get_ti_counts(os.path.join(path, 'data'), index1, index2 )
                outsheet.write(j, 4, ti_counts)
                index2=index2+1


    out_workbook.save(os.path.join(path, 'out.xls'))
def get_index1(str0):

    x=[ '一', '二',  '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六' ]
    chapter = re.findall(r'第(.{1,2})章', str0)
    try:
        return int(chapter[0])
    except:
        i = x.index(chapter[0])
        return i + 1



def get_index2(str0, index1):
    x=[ '一', '二',  '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六' ]

    index2 = re.findall(r'第(.{1,2})节', str0)
    if '节' in str0:   ###“第X节”的模式匹配
        index2 = re.findall(r'第(.{1,2})节', str0)
        try:
            return int(index2[0])
        except:
            i=x.index(index2[0])
            return i+1
    elif True      :#  "1.1"的模式匹配
        pass
    elif   True       : ##"1 数列极限的匹配"
        pass
def get_ti_counts( path, index1, index2 ):
    file_list=os.listdir(path)
    for i in range(1,100):
        x=str(index1)+'.'+ str(index2) +'-'+str(i)+'.png'
        if not x in file_list:
            return i-1

#----------------main--------------
path='D:\\松鼠搜题\\最终版\\微积分-第二版-吴传生'
update_conf(path)